//
//  NewBookCell.swift
//  clreader
//
//  Created by colin on 2019/4/11.
//  Copyright © 2019 colin. All rights reserved.
//

import UIKit

class NewBookCell: UITableViewCell {

    var selectedHandle:((_ goods:JSONObject?)->Void)?
    
    static let reuseId = "NewBookCell"
    
    static var cellHeight:CGFloat {
        return 160.0
    }
    
    private var contentCollectionView:UICollectionView?
    
    private var datas:[JSONObject]?
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        self.do {
            $0.selectionStyle = .none
            $0.backgroundColor = UIColor.clear
            $0.contentView.backgroundColor = UIColor.clear
            
            let layout = UICollectionViewFlowLayout()
            layout.scrollDirection = .horizontal
            let collectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: layout).then {
                $0.dataSource = self
                $0.delegate = self
                $0.showsVerticalScrollIndicator = false
                $0.showsHorizontalScrollIndicator = false
                $0.backgroundColor = UIColor.clear
                $0.decelerationRate = UIScrollView.DecelerationRate.fast
                $0.register(NewBookContentCell.self, forCellWithReuseIdentifier: "NewBookContentCell")
            }
            self.contentCollectionView = collectionView
            self.contentView.addSubview(collectionView)
            collectionView.snp.makeConstraints { (make) in
                make.edges.equalToSuperview()
            }
        }
        
    }
    
    func refresh(_ datas:[JSONObject]?) {
        self.datas = datas
        self.contentCollectionView?.reloadData()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
}


//MARK: UICollectionViewDataSource
extension NewBookCell : UICollectionViewDataSource {
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        if let datas_ = self.datas {
            return datas_.count
        } else {
            return 0
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "NewBookContentCell", for: indexPath) as! NewBookContentCell
        if let datas_ = self.datas , indexPath.item < datas_.count {
            cell.refresh(datas_[indexPath.item])
        }
        return cell
    }
    
}

//MARK:UICollectionViewDelegateFlowLayout
extension NewBookCell : UICollectionViewDelegateFlowLayout {
    
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        if let datas_ = self.datas , !datas_.isEmpty, datas_.count > indexPath.item {
            self.selectedHandle?(datas_[indexPath.item])
        }
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
        return UIEdgeInsets(top: 0, left: 0, bottom: 0, right: 15.0)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
        return CGSize(width: UIScreen.main.bounds.width - 80.0, height: NewBookCell.cellHeight)
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat {
        return 0.0
    }
    
    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat {
        return 0.0
    }
}

extension NewBookCell {
    class NewBookContentCell: UICollectionViewCell {
        
        private lazy var imageViewPhoto = UIImageView()
        private lazy var labelName = UILabel()
        private lazy var labelAuthor = UILabel()
        private lazy var labelIntro = UILabel()

        override init(frame: CGRect) {
            super.init(frame: CGRect.zero)
            self.contentView.backgroundColor = UIColor.clear
            
            self.imageViewPhoto.do {
                $0.layer.cornerRadius = 3.0
                $0.layer.masksToBounds = true
            }
            self.contentView.addSubview(self.imageViewPhoto)
            self.imageViewPhoto.snp.makeConstraints { (make) in
                make.size.equalTo(CGSize(width: 80.0, height: 111.0))
                make.left.equalToSuperview().offset(15.0)
                make.centerY.equalToSuperview()
            }
            
            self.labelName.do {
                $0.textColor = UIColor(hex: "343434")
                $0.font = UIFont.systemFont(ofSize: 15.0, weight: .regular)
            }
            self.contentView.addSubview(self.labelName)
            self.labelName.snp.makeConstraints { (make) in
                make.left.equalTo(self.imageViewPhoto.snp.right).offset(15.0)
                make.top.equalTo(self.imageViewPhoto.snp.top)
                make.right.equalToSuperview().offset(-15.0)
            }
            
            self.labelAuthor.do {
                $0.textColor = UIColor(hex: "828282")
                $0.font = UIFont.systemFont(ofSize: 12.0, weight: .light)
            }
            self.contentView.addSubview(self.labelAuthor)
            self.labelAuthor.snp.makeConstraints { (make) in
                make.left.equalTo(self.imageViewPhoto.snp.right).offset(15.0)
                make.top.equalTo(self.labelName.snp.bottom).offset(5.0)
                make.right.equalToSuperview().offset(-15.0)
            }
            
            let introContainer = UIView().then {
                $0.backgroundColor = UIColor(hex: "f8f8f8")
                $0.layer.cornerRadius = 3.0
                $0.layer.masksToBounds = true
                
                self.labelIntro.do {
                    $0.numberOfLines = 4
                    $0.textColor = UIColor(hex: "343434")
                    $0.font = UIFont.systemFont(ofSize: 12.0, weight: .light)
                }
                $0.addSubview(self.labelIntro)
                self.labelIntro.snp.makeConstraints({ (make) in
                    make.left.top.equalToSuperview().offset(10.0)
                    make.bottom.right.equalToSuperview().offset(-10.0)
                })
            }
            self.contentView.addSubview(introContainer)
            introContainer.snp.makeConstraints { (make) in
                make.left.equalTo(self.imageViewPhoto.snp.right).offset(15.0)
                make.top.equalTo(self.labelAuthor.snp.bottom).offset(5.0)
                make.right.equalToSuperview()
            }
            
        }
        
        func refresh(_ data:JSONObject?) {
            self.labelName.text = data?["title"] as? String
            self.labelAuthor.text = data?["author"] as? String
            
            if let intro = data?["marketing"] as? String {
                self.labelIntro.attributedText = intro.htmlAttributedString
            } else {
                self.labelIntro.text = ""
            }
            
            // 图片
            if let cover_url = data?["cover_url"] as? String,!cover_url.isEmpty,
                let baseUrl = URL(string: Router.baseUrl) {
                let imageUrl = baseUrl.appendingPathComponent(cover_url)
                self.imageViewPhoto.kf.setImage(with: imageUrl)
            } else {
                self.imageViewPhoto.image = nil
            }
            
        }
        
        required init?(coder aDecoder: NSCoder) {
            fatalError("init(coder:) has not been implemented")
        }
    }
}

